<?php
/**
 * CRMLite Client Controller
 *
 * @final
 * @package Crmlite_App
 * @version $Id: ClientController.php 66 2007-09-10 08:13:09Z etng2004 $
 * @copyright 2006-2007 ETE.CN
 * @author Yi BO  <etng2004@gmail.com>
 * @license PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */
require_once dirname(__FILE__) . '/AdminBaseController.php';
final class Admin_ClientController extends AdminBaseController
{
    /**
	 * 默认的模型
	 *
	 * 未初始化时是字符串，初始化之后就是一个模型接口
	 *
	 * @var ClientModel
	 */
    protected $model = 'Client';

    public function init()
    {
        parent::init();
        $this->pushPoint('客户管理');
    }
    public function indexAction()
    {
        $this->log('Client Index page called!');
        $this->_forward('list');
    }
    public function addAction()
    {
        $record = array();
         $record['created_by'] = $this->S_staff_id;
         $record['stage'] = 2;
        if($this->isPost())
        {
            $record = array_merge($_POST['fields']['client'], $record);
            $record['created_at'] = time();
            $this->S_staff['client_type'] == 'ALL' || $record['client_type_code'] = $this->S_staff['client_type'];
            if($this->model->insert($record))
            {
                $this->removeCache();
                $this->log($msg = "Client #{$record['id']} created!");
                $rediect_url = $this->getHistory($this->base_url, array('action' => 'list'));
                $this->feedback($msg, '成功', $rediect_url);
            }
            $this->view->message = $this->model->getErrors();
        }
        else
        {
            $record = array_merge($this->model->getDefaults(), $record);
        }
        $this->view->client = $record;
        $this->setTitle('新增客户');
    }

    public function batchOperateAction()
    {
        /**
    	 * WE do not need render from template!
    	 */
        $this->_helper->viewRenderer->setNoRender();
        if($this->isPost())
        {
            var_dump($_POST);
        }
    }

    public function editAction()
    {
        if($this->isPost())
        {
            $record = $_POST['fields'];
            $id = $record['id'];
            $record['updated_at'] = time();
            if($this->model->update($record, "id={$id}"))
            {
                $this->removeCache();
                $this->log($msg = "Client #{$record['id']} updated!");
                $this->feedback($msg, '成功', $this->base_url);
            }
            $this->view->client = $record;
            $error = 'Update failed!';
        }
        /**
    	 * 若不是POST方法则为初始编辑
    	 */
        $this->setTitle('修改客户资料');
        if(empty($error))
        {
            $id = intval($this->_getParam('id', 0));
            $this->view->client = $this->model->find($id);
        }
    }
    /**
     * 删除缓存
     *
     * 如果不指定记录ID，则默认删除所有相应的缓存
     *
     * @param int $id
     * @todo 实现删除所有的功能
     */
    protected function removeCache( $id = null )
    {
        $Cache = Zend_Registry::get('cache');
        /* @var $Cache Zend_Cache_Core */
        $Cache->remove('admin_Client_feed_data');
        $Cache->remove('client_feed_data');
    }
    /**
	 * 分页列举
	 *
	 */
    public function listAction()
    {
        $where = array();
        if($this->S_staff['ROLE'] != 'ADMIN')
        {
            $where[] = "created_by = {$this->S_staff_id}";
        }
        if($this->S_staff['client_type'] !== 'ALL')
        {
            $where += array(
            "client_type_code = '{$this->S_staff['client_type']}'",
            'deleted_at = 0 OR DATE(FROM_UNIXTIME(deleted_at)) <= CURDATE()',
            );
        }
        $this->view->mode = 'list';
        if($this->isPost())
        {
            if(isset($_POST['qsearch']['keyword']))
            {
                $keyword =trim(strip_tags(($_POST['qsearch']['keyword'])));
                $where[] = "
				company like '%{$keyword}%'
				OR
				website like '%{$keyword}%'
				";
                $this->view->mode = 'search';
            }
            elseif (isset($_POST['search']['client']))
            {
                $company = trim(strip_tags(($_POST['search']['client']['company'])));
                $website = trim(strip_tags(($_POST['search']['client']['website'])));
                $a = array();
                empty($company)	||  $a[] = "company like '%{$company}%'";
                empty($website)	||  $a[] = "website like '%{$website}%'";
                empty($a)		||  $where[] = implode(' OR ', $a);
                $this->view->mode = 'advance_search';
            }
        }
        $default_statics = array_fill_keys(array_keys($this->trade_types), 0);
        $this->view->statics = $this->model->statics($where, 'trade_type_id', $default_statics);
        if($trade = intval($this->_getParam('trade', 0)))
        {
            $where[] = 'trade_type_id = ' . $trade;
        }
        $order = 'created_at DESC';
        $pager = array(
        'curpage' 	=> $this->_getParam('page', 1),
        'perpage'	=> $this->_getParam('perpage', 10),
        'total'		=> $this->model->count($where),
        'url'		=> $this->base_url . '/list',
        );

        $this->view->pager = $pager;
        $this->view->clients = $this->model->paginate($where, $order, $pager['curpage'], $pager['perpage']);
        if($trade)
        {
            $this->setTitle($this->trade_types[$trade], $this->view->statics[$trade]);
        }
        else
        {
            $this->setTitle('所有', $pager['total']);
        }
        if($this->view->mode =='search')
        {
            $this->setTitle("关键词“{$keyword}”的搜索结果", $pager['total']);
        }
    }
    /**
	 * 搜索
	 *
	 */
    public function searchAction()
    {
        $this->setTitle('高级搜索');
    }

    public function viewAction()
    {
        $id = intval($this->_getParam('id', 1));
        $client = $this->model->find($id);
        if($this->S_staff['ROLE'] !='ADMIN' && $client['created_by'] != $this->S_staff_id)
        {
            $client = null;
        }
        if(!$client)exit('无此客户！');
        $Contact = new ContactModel();

        $where = array(
        'deleted_at = 0',
        'client_id = ' . $client['id']
        );
        $this->view->contacts =$Contact->findAll($where, 'created_at DESC', 5);

        $ContactHistory = new ContactHistoryModel();
        $where = array(
        'client_id = ' . $client['id'],
        );
        $this->view->contact_histories = $ContactHistory->findAll($where, 'report_at DESC', 5);
        $this->view->client = $client;
        $this->setTitle($client['company']);
    }
    /**
     * 删除记录，默认为标记删除
     *
     */
    public function trashAction()
    {
        $id = intval($this->_getParam('id', 1));
        if($id)
        {
            if($status = $this->model->trashById($id))
            {
                $this->removeCache();
                $this->log($msg = "Client #{$id} now is marked as deleted!");
                $this->feedback($msg, '成功', $this->base_url);
            }
        }
        echo $status;
        exit();
    }
    /**
     * 恢复标记删除的记录
     *
     */
    public function restoreAction()
    {
        $id = intval($this->_getParam('id', 1));
        if($id)
        {
            if($status = $this->model->restoreById($id))
            {
                $this->removeCache();
                $this->log($msg = "now Client #{$id} is marked as normal(undeleted)!");
                $this->feedback($msg, '成功', $this->base_url);
            }
        }
        echo $status;
        exit();
    }
    /**
	 * 删除指定的记录
	 *
	 */
    public function deleteAction()
    {
        $id = intval($this->_getParam('id', 1));
        if($id)
        {
            if($status = $this->model->deleteById($id))
            {
                $this->removeCache();
                $this->log($msg = "Client #{$id} deleted!");
                $this->feedback($msg, '成功', $this->base_url);
            }
        }
        echo $status;
        exit();
    }
    /**
     * 检查是否有撞单，如有，显示相关信息供内部联系
     *
     */
    public function existAction()
    {
        if($this->isPost())
        {
            $where = $or_where = array();
            $client_type = ($this->S_staff['ROLE'] == 'ADMIN')? $_POST['client_exsit']['client_type_code']:
            $this->S_staff['client_type'];
            unset($_POST['client_exsit']['client_type_code']);
            $where[] = "client_type_code = '{$client_type}'";
            $fields = $_POST['client_exsit'];
            array_walk($fields, create_function('&$s', 'trim(strip_tags($s));'));
            $this->view->data = $fields;
            if($this->model->isOrderConflict($fields['company'], $fields['website'], $where, $mohu = true))
            {
                $this->view->conflict_clients = $this->model->findAll($where);
            }
        }
        $this->setTitle("防撞单查询");
    }
    public function contactAction()
    {
        $id = intval($this->_getParam('id', 1));
        $mContact = new ContactModel();
        $where = array(
        'client_id = ' . $id,
        );
        $this->view->contacts = $mContact->findAll($where, '', 10);
    }
}
